const axios = require('axios');

(async () => {
  console.log('🔍 深度诊断勋章显示问题...');
  
  try {
    // 1. 登录用户
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      email: 'admin@campus.com',
      password: 'admin123'
    });
    
    const authToken = loginResponse.data.token;
    const userId = loginResponse.data.user.id;
    console.log(`✅ 用户登录成功: ID=${userId}, Username=${loginResponse.data.user.username}`);
    
    // 2. 测试不同的勋章API调用
    console.log('\n🏆 测试勋章API不同调用方式...');
    
    // 调用1：获取所有勋章（无筛选）
    const allBadgesResponse = await axios.get('http://localhost:3000/api/badges');
    console.log(`📊 /api/badges (全部): ${allBadgesResponse.data.badges.length}个勋章`);
    
    // 调用2：获取用户拥有的勋章
    const ownedBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=owned', {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    console.log(`🎖️ /api/badges?filter=owned: ${ownedBadgesResponse.data.badges.length}个勋章`);
    
    // 调用3：获取可获得的勋章
    const availableBadgesResponse = await axios.get('http://localhost:3000/api/badges?filter=available');
    console.log(`🆔 /api/badges?filter=available: ${availableBadgesResponse.data.badges.length}个勋章`);
    
    // 调用4：获取徽章进度
    try {
      const progressResponse = await axios.get('http://localhost:3000/api/badges/progress', {
        headers: { Authorization: `Bearer ${authToken}` }
      });
      console.log(`📈 /api/badges/progress: 进度${progressResponse.data.progress}%`);
      console.log(`   已获得: ${progressResponse.data.earned}, 可获得: ${progressResponse.data.available}`);
    } catch (progressError) {
      console.log(`❌ 获取进度失败: ${progressError.message}`);
    }
    
    // 3. 分析现有勋章的详细信息
    console.log('\n📋 所有勋章详细分析:');
    
    allBadgesResponse.data.badges.forEach((badge, index) => {
      const isUserBadge = badge.user_id === userId;
      console.log(`勋章 ${index + 1}: ${badge.badge_name || 'Unknown'}`);
      console.log(`  - ID: ${badge.id}`);
      console.log(`  - 所有者ID: ${badge.user_id}`);
      console.log(`  - 状态: ${badge.status}`);
      console.log(`  - 活动ID: ${badge.activity_id}`);
      console.log(`  - 活动名称: ${badge.activity?.title || '无'}`);
      console.log(`  - 是否当前用户: ${isUserBadge ? '✅' : '❌'}`);
      console.log('');
    });
    
    // 4. 检查是否存在模板勋章或其他类型
    console.log('\n🔍 检查勋章类型分布:');
    
    const statusCounts = {};
    allBadgesResponse.data.badges.forEach(badge => {
      statusCounts[badge.status] = (statusCounts[badge.status] || 0) + 1;
    });
    
    console.log('勋章状态统计:');
    Object.entries(statusCounts).forEach(([status, count]) => {
      console.log(`  - ${status}: ${count}个`);
    });
    
    // 5. 检查活动数量，看是否应该有更多勋章
    console.log('\n📅 检查活动和勋章的关系:');
    
    const activitiesResponse = await axios.get('http://localhost:3000/api/activities');
    console.log(`🎯 系统活动总数: ${activitiesResponse.data.activities.length}`);
    console.log(`🏆 系统勋章总数: ${allBadgesResponse.data.badges.length}`);
    
    if (activitiesResponse.data.activities.length > allBadgesResponse.data.badges.length) {
      console.log('⚠️ 发现问题：活动数量多于勋章数量');
      console.log('   可能存在没有对应勋章的活动');
    }
    
    // 6. 检查最近的几个活动是否有勋章
    console.log('\n🔍 检查活动是否都有对应勋章:');
    
    const recentActivities = activitiesResponse.data.activities.slice(0, 5);
    recentActivities.forEach((activity, index) => {
      const hasBadge = allBadgesResponse.data.badges.some(badge => badge.activity_id === activity.id);
      console.log(`活动 ${index + 1}: ${activity.title}`);
      console.log(`  - ID: ${activity.id}`);
      console.log(`  - 状态: ${activity.status || 'unknown'}`);
      console.log(`  - 有对应勋章: ${hasBadge ? '✅' : '❌'}`);
      console.log('');
    });
    
  } catch (error) {
    console.error('❌ 诊断过程出错:', error.message);
    if (error.response) {
      console.error('详细错误:', error.response.data);
    }
  }
})(); 